package conf

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/pflag"
	"github.com/spf13/viper"
)

const defaultConfigFile = "../config.yaml"

func Init() (conf *Config, err error) {

	pflag.StringP("conf", "c", "", "choose conf file.")
	pflag.Parse()

	v := viper.New()
	v.BindPFlags(pflag.CommandLine)

	configFile := v.GetString("conf")
	if configFile == "" {
		configFile = defaultConfigFile
	}

	viper.SetConfigFile(configFile)
	//读取配置信息
	err = viper.ReadInConfig()
	if err != nil {
		// 读取配置信息失败
		fmt.Printf("viper.ReadInConfig failed, err:%v\n", err)
		return
	}

	// 把读取到的配置信息反序列化到 Conf 变量中
	if err := viper.Unmarshal(&conf); err != nil {
		fmt.Printf("viper.Unmarshal failed, err:%v\n", err)
	}

	// 配置文件监听
	viper.WatchConfig()
	viper.OnConfigChange(func(in fsnotify.Event) {
		fmt.Println("配置文件修改了...")
		if err := viper.Unmarshal(&conf); err != nil {
			fmt.Printf("viper.Unmarshal failed, err:%v\n", err)
		}
	})

	return
}
